package cn.edu.xmist.supermarketsys.controller;

import cn.edu.xmist.supermarketsys.Util.ObjtoLayJson;
import cn.edu.xmist.supermarketsys.Util.Strs;
import cn.edu.xmist.supermarketsys.entity.Product;
import cn.edu.xmist.supermarketsys.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    public static String[] columns = {"id", "name", "price", "num", "houseCode", "supplierCode"};

    @RequestMapping("/list")
    public String list(Integer page, Integer limit) throws Exception {
        List<Product> list = productService.list();
        List<Product> pageList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (i >= (page - 1) * limit && i < page * limit) {
                pageList.add(list.get(i));
            }
        }
        return ObjtoLayJson.ListtoJson(pageList, columns);
    }

    @RequestMapping("/pageList")
    public String pageList(Integer page, Integer limit, Product product) throws Exception {
        System.out.println(product.toString() + "1111");
        List<Product> pageList = productService.selectPage(product, page, limit);
        String[] column = {"id", "name", "price", "num", "houseCode", "supplierCode", "houseName", "supplierName"};
        return ObjtoLayJson.ListtoJson(pageList, column);
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Product product) {
        Boolean flag = productService.saveOrUpdate(product);
        return Strs.SUCCESS_RETURN_JSON;
    }

    @RequestMapping("/deleteById")
    public String deleteById(Long id) {
        Boolean flag = productService.removeById(id);
        return Strs.SUCCESS_RETURN_JSON;
    }

}
